package com.sinvo.oa.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sinvo.oa.entity.model.system.SysPost;
import com.sinvo.oa.entity.vo.system.SysPostQueryVo;
import com.sinvo.oa.exception.CustomException;
import com.sinvo.oa.mapper.SysPostMapper;
import com.sinvo.oa.result.ResultCode;
import com.sinvo.oa.service.SysPostService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * @Description SysPostService实现类
 */
@Service
public class SysPostServiceImpl extends ServiceImpl<SysPostMapper, SysPost> implements SysPostService {

    @Override
    public Page<SysPost> findPostByPage(Page<SysPost> page, SysPostQueryVo sysPostQueryVo) {
        LambdaQueryWrapper<SysPost> queryWrapper = new LambdaQueryWrapper<>();
        //获取输入值
        String name = sysPostQueryVo.getName();
        String postCode = sysPostQueryVo.getPostCode();
        //判断条件
        if (!StringUtils.isEmpty(name)) {
            queryWrapper.like(SysPost::getName, name);
        }
        if (!StringUtils.isEmpty(postCode)) {
            queryWrapper.like(SysPost::getPostCode, postCode);
        }
        Page<SysPost> pageModel = this.page(page, queryWrapper);
        return pageModel;
    }

    @Override
    public void savePost(SysPost sysPost) {
        LambdaQueryWrapper<SysPost> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysPost::getName,sysPost.getName());
        int count = this.count(queryWrapper);
        if (count > 0) {
            throw new CustomException(ResultCode.DATA_ERROR.getCode(), "岗位名重复");
        }
        boolean success = this.save(sysPost);
        if (!success) {
            throw new CustomException(ResultCode.SERVICE_ERROR.getCode(), "新增失败，请重试");
        }
    }

    @Override
    public void updatePost(SysPost sysPost) {
        LambdaQueryWrapper<SysPost> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysPost::getName,sysPost.getName());
        SysPost one = this.getOne(queryWrapper);
        if (one != null && one.getId() != sysPost.getId()){
            throw new CustomException(ResultCode.DATA_ERROR.getCode(), "岗位名重复");
        }
        boolean success = this.updateById(sysPost);
        if (!success) {
            throw new CustomException(ResultCode.SERVICE_ERROR.getCode(), "更新失败，请重试");
        }
    }

    @Override
    public boolean changeStatus(Long id, Integer status) {
        SysPost post = this.getById(id);
        post.setStatus(status);
        this.updateById(post);
        return true;
    }
}
